package info.motteke.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Closer {

    public void close(InputStream is) {
        if (is == null) {
            return;
        }

        try {
            is.close();
        } catch (IOException e) {
            onIOError(e);
        }
    }

    public void close(Reader r) {
        if (r == null) {
            return;
        }

        try {
            r.close();
        } catch (IOException e) {
            onIOError(e);
        }
    }

    public void close(OutputStream os) {
        if (os == null) {
            return;
        }

        try {
            os.close();
        } catch (IOException e) {
            onIOError(e);
        }
    }

    public void close(Writer w) {
        if (w == null) {
            return;
        }

        try {
            w.close();
        } catch (IOException e) {
            onIOError(e);
        }
    }

    public void close(ResultSet rs) {
        if (rs == null) {
            return;
        }

        try {
            rs.close();
        } catch (SQLException e) {
            onSQLError(e);
        }
    }

    public void close(Statement stmt) {
        if (stmt == null) {
            return;
        }

        try {
            stmt.close();
        } catch (SQLException e) {
            onSQLError(e);
        }
    }

    public void close(Connection con) {
        if (con == null) {
            return;
        }

        try {
            con.close();
        } catch (SQLException e) {
            onSQLError(e);
        }
    }

    protected void onIOError(IOException cause) {
        /* empty */
    }

    protected void onSQLError(SQLException cause) {
        /* empty */
    }
}
